package com.huanzhidadi.java8inaction.chapter4;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 构建流的方法
 */
public class CreateStreamTest {
    public static void main(String[] args) {
        // 由值创建流 Stream.of
        Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
        stream.map(String::toUpperCase).forEach(System.out::print);
        System.out.println("\r\n-----------------------------------------");

        // 由数组创建流 Arrays.stream
        int[] numbers = {2, 3, 5, 7, 11, 13};
        int sum = Arrays.stream(numbers).sum();
        System.out.println(sum);
        System.out.println("-----------------------------------------");

        // 由文件生成流 Files.lines 返回一个由指定文件中的各行构成的字符串流
        long uniqueWords = 0;
        try (Stream<String> lines =
                     Files.lines(Paths.get("D:\\IdeaProjects\\java-interview-collect\\java8InAction\\src\\main\\resources\\data.txt"),
                Charset.defaultCharset())) {
            uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
                    .distinct()
                    .count();
//            lines.flatMap(line -> Arrays.stream(line.split(" "))).forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(uniqueWords);
        System.out.println("-----------------------------------------");

        // 由函数生成流：创建无限流
        // iterate 接受一个初始值，和一个指定规则的Lambda表达式
        Stream.iterate(0, n -> n + 2)
                .limit(10)
                .forEach(System.out::println);
        System.out.println("-----------------------------------------");

        // generate 接受一个Supplier<T>类型的入参
        Stream.generate(Math::random)
                .limit(5)
                .forEach(System.out::println);

    }
}
